

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/HexoPage/img/favicon.jpeg">
  <link rel="icon" href="/HexoPage/img/favicon.jpeg">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="xiaoaodi">
  <meta name="keywords" content="">
  
    <meta name="description" content="#目录 [TOC] 一、Ajax简介AJAX 简介 AJAX 全称为 Asynchronous JavaScript And XML，就是异步的 JS 和 XML。 通过 AJAX 可以在浏览器中向服务器发送异步请求，最大的优势：无刷新获取数据。 AJAX 不是新的编程语言，而是一种将现有的标准组合在一起使用的新方式。 1. XML简介 XML 可扩展标记语言。 XML 被设计用来传输和存储数据。">
<meta property="og:type" content="article">
<meta property="og:title" content="Ajax学习记录(详解)">
<meta property="og:url" content="http://xiao_aodi.gitee.io/hexopage/2022/03/23/Ajax%E8%AE%B0%E5%BD%95(%E8%AF%A6%E8%A7%A3)/index.html">
<meta property="og:site_name" content="~吃椰子灰的胖丁">
<meta property="og:description" content="#目录 [TOC] 一、Ajax简介AJAX 简介 AJAX 全称为 Asynchronous JavaScript And XML，就是异步的 JS 和 XML。 通过 AJAX 可以在浏览器中向服务器发送异步请求，最大的优势：无刷新获取数据。 AJAX 不是新的编程语言，而是一种将现有的标准组合在一起使用的新方式。 1. XML简介 XML 可扩展标记语言。 XML 被设计用来传输和存储数据。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-03-23T14:30:00.000Z">
<meta property="article:modified_time" content="2022-03-23T09:51:48.630Z">
<meta property="article:author" content="xiaoaodi">
<meta name="twitter:card" content="summary_large_image">
  
  
  <title>Ajax学习记录(详解) - ~吃椰子灰的胖丁</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/HexoPage/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"xiao_aodi.gitee.io","root":"/HexoPage/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":false,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/HexoPage/local-search.xml"};
  </script>
  <script  src="/HexoPage/js/utils.js" ></script>
  <script  src="/HexoPage/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 6.1.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/HexoPage/">
      <strong>Xiao_aodi</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>
   
      <!-- 天气网 -->
      


    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/HexoPage/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/HexoPage/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/HexoPage/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/HexoPage/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/HexoPage/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/HexoPage/img/wallhaven-wqve97.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="Ajax学习记录(详解)">
              
            </span>
            
              <div class="mt-3">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-author" aria-hidden="true"></i>
      xiaoaodi
    </span>
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2022-03-23 22:30" pubdate>
        2022年3月23日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      18k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      154 分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Ajax学习记录(详解)</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：2022年3月23日 下午
                
              </p>
            
            <div class="markdown-body">
              <h1 id="目录"><a href="#目录" class="headerlink" title="#目录"></a>#目录</h1><hr>
<p>[TOC]</p>
<h1 id="一、Ajax简介"><a href="#一、Ajax简介" class="headerlink" title="一、Ajax简介"></a>一、Ajax简介</h1><p>AJAX 简介 AJAX 全称为 Asynchronous JavaScript And XML，就是异步的 JS 和 XML。</p>
<p>通过 AJAX 可以在浏览器中向服务器发送异步请求，最大的优势：<code>无刷新获取数据</code>。</p>
<p>AJAX 不是新的编程语言，而是一种将现有的标准组合在一起使用的新方式。</p>
<h2 id="1-XML简介"><a href="#1-XML简介" class="headerlink" title="1. XML简介"></a>1. XML简介</h2><ol>
<li>XML 可扩展标记语言。</li>
<li>XML 被设计用来传输和存储数据。 </li>
<li>XML 和 HTML 类似，不同的是 HTML 中都是预定义标签，而 XML 中没有预定义标签， 全都是自定义标签，用来表示一些数据。</li>
</ol>
<p>比如说我有一个学生数据：<br>name &#x3D; “aodi” ; age &#x3D; 22; gender &#x3D; “男” ;</p>
<figure class="highlight xml"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></div></td><td class="code"><pre><code class="hljs xml">用 XML 表示：<br><span class="hljs-tag">&lt;<span class="hljs-name">student</span>&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">name</span>&gt;</span>aodi<span class="hljs-tag">&lt;/<span class="hljs-name">name</span>&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">age</span>&gt;</span>22<span class="hljs-tag">&lt;/<span class="hljs-name">age</span>&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">gender</span>&gt;</span>男<span class="hljs-tag">&lt;/<span class="hljs-name">gender</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">student</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>现在已经被 JSON 取代了。</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-punctuation">&#123;</span><span class="hljs-attr">&quot;name&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;aodi&quot;</span><span class="hljs-punctuation">,</span><span class="hljs-attr">&quot;age&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-number">22</span><span class="hljs-punctuation">,</span><span class="hljs-attr">&quot;gender&quot;</span><span class="hljs-punctuation">:</span><span class="hljs-string">&quot;男&quot;</span><span class="hljs-punctuation">&#125;</span><br></code></pre></td></tr></table></figure>

<h2 id="2-Ajax的特点"><a href="#2-Ajax的特点" class="headerlink" title="2. Ajax的特点"></a>2. Ajax的特点</h2><h3 id="2-1-AJAX-的优点"><a href="#2-1-AJAX-的优点" class="headerlink" title="2.1 AJAX 的优点"></a>2.1 AJAX 的优点</h3><ol>
<li><p>可以无需刷新页面而与服务器端进行通信。 </p>
</li>
<li><p>允许你根据用户事件来更新部分页面内容。</p>
</li>
</ol>
<h3 id="2-2-Ajax的缺点"><a href="#2-2-Ajax的缺点" class="headerlink" title="2.2 Ajax的缺点"></a>2.2 Ajax的缺点</h3><ol>
<li><p>没有浏览历史，不能回退</p>
</li>
<li><p>存在跨域问题(同源)</p>
</li>
<li><p>SEO 不友好</p>
</li>
</ol>
<h2 id="3-HTTP简介"><a href="#3-HTTP简介" class="headerlink" title="3. HTTP简介"></a>3. HTTP简介</h2><p>HTTP（hypertext transport protocol）协议『超文本传输协议』，协议详细规定了浏览器和万维网服务器之间互相通信的规则、约定,、规则</p>
<h3 id="3-1-请求报文"><a href="#3-1-请求报文" class="headerlink" title="3.1 请求报文"></a>3.1 请求报文</h3><p><code>重点是格式与参数</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs js">行   <span class="hljs-variable constant_">POST</span> /s?ie=utf-<span class="hljs-number">8</span> <span class="hljs-variable constant_">HTTP</span>/<span class="hljs-number">1.1</span> <br><br>头   <span class="hljs-title class_">Host</span>: atguigu.<span class="hljs-property">com</span><br>​    <span class="hljs-title class_">Cookie</span>: name=guigu<br>​    <span class="hljs-title class_">Content</span>-<span class="hljs-attr">type</span>: application/x-www-form-urlencoded<br>​    <span class="hljs-title class_">User</span>-<span class="hljs-title class_">Agent</span>: chrome <span class="hljs-number">83</span><br>空行<br>体   username=admin&amp;password=admin<br></code></pre></td></tr></table></figure>

<h3 id="3-2-响应报文"><a href="#3-2-响应报文" class="headerlink" title="3.2 响应报文"></a>3.2 响应报文</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs js">行   <span class="hljs-variable constant_">HTTP</span>/<span class="hljs-number">1.1</span> <span class="hljs-number">200</span> <span class="hljs-variable constant_">OK</span><br><br>头   <span class="hljs-title class_">Content</span>-<span class="hljs-title class_">Type</span>: text/html;charset=utf-<span class="hljs-number">8</span><br>​    <span class="hljs-title class_">Content</span>-<span class="hljs-attr">length</span>: <span class="hljs-number">2048</span><br>​    <span class="hljs-title class_">Content</span>-<span class="hljs-attr">encoding</span>: gzip<br>空行  <br>体   &lt;html&gt;<br>​      &lt;head&gt;<br>​      &lt;/head&gt;<br>​      &lt;body&gt;<br>​        &lt;h1&gt;aodi&lt;/h1&gt;<br>​      &lt;/body&gt;<br>​    &lt;/html&gt;<br></code></pre></td></tr></table></figure>

<h3 id="3-3-Chrome网络控制台查看通信报文"><a href="#3-3-Chrome网络控制台查看通信报文" class="headerlink" title="3.3 Chrome网络控制台查看通信报文"></a>3.3 Chrome网络控制台查看通信报文</h3><p>1、Network  –&gt; Hearders  请求头</p>
<p>2、Network  –&gt; Response 响应体:通常返回的是html</p>
<h1 id="二、原生Ajax"><a href="#二、原生Ajax" class="headerlink" title="二、原生Ajax"></a>二、原生Ajax</h1><p>1、XMLHttpRequest，AJAX 的所有操作都是通过该对象进行的。</p>
<p>2、当你前端想设置自定义的请求头时,需要如此后端设置响应头</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">//表示接收任意类型的请求							</span><br>app.<span class="hljs-title function_">all</span>(<span class="hljs-string">&#x27;/server&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> &#123; <span class="hljs-comment">//响应头 允许跨域     运行自定义响应头</span><br> response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Origin&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>); response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Headers&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);&#125;<br></code></pre></td></tr></table></figure>

<p>3、<code>ajax请求状态</code>:xhr.readyState<br>    0：请求未初始化，还没有调用 open()。</p>
<p>​    1：请求已经建立，但是还没有发送，还没有调用 send()。</p>
<p>​    2：请求已发送，正在处理中（通常现在可以从响应中获取内容头）。</p>
<p>​    3：请求在处理中；通常响应中已有部分数据可用了，没有全部完成。</p>
<p>​    4：响应已完成；您可以获取并使用服务器的响应了</p>
<h2 id="1-Ajax的使用"><a href="#1-Ajax的使用" class="headerlink" title="1. Ajax的使用"></a>1. Ajax的使用</h2><p>使用步骤:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-number">1</span>) 创建 <span class="hljs-title class_">XMLHttpRequest</span> 对象<br><span class="hljs-keyword">var</span> xhr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">XMLHttpRequest</span>();<br><span class="hljs-number">2</span>) 设置请求信息<br>xhr.<span class="hljs-title function_">open</span>(method, url);<br><span class="hljs-comment">//可以设置请求头，一般不设置</span><br>xhr.<span class="hljs-title function_">setRequestHeader</span>(<span class="hljs-string">&#x27;Content-Type&#x27;</span>, <span class="hljs-string">&#x27;application/x-www-form-urlencoded&#x27;</span>);<br><span class="hljs-number">3</span>) 发送请求<br>xhr.<span class="hljs-title function_">send</span>(body) <span class="hljs-comment">//get 请求不传 body 参数，只有 post 请求使用</span><br><span class="hljs-number">4</span>) 接收响应<br><span class="hljs-comment">//xhr.responseXML 接收 xml 格式的响应数据</span><br><span class="hljs-comment">//xhr.responseText 接收文本格式的响应数据</span><br>xhr.<span class="hljs-property">onreadystatechange</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>)&#123;<br><span class="hljs-keyword">if</span>(xhr.<span class="hljs-property">readyState</span> == <span class="hljs-number">4</span> &amp;&amp; xhr.<span class="hljs-property">status</span> == <span class="hljs-number">200</span>)&#123;<br><span class="hljs-keyword">var</span> text = xhr.<span class="hljs-property">responseText</span>;<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(text);<br>&#125;&#125;<br></code></pre></td></tr></table></figure>

<h3 id="1-1-Get方式"><a href="#1-1-Get方式" class="headerlink" title="1.1 Get方式"></a>1.1 Get方式</h3><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs html">//绑定事件<br>btn.onclick = function () &#123;<br>  //1. 创建对象<br>  const xhr = new XMLHttpRequest();<br>  //2. 初始化 设置请求方法和 url<br>  xhr.open(&#x27;GET&#x27;, &#x27;http://127.0.0.1:8000/server?a=100&amp;b=200&amp;c=300&#x27;);<br>  //3. 发送<br>  xhr.send();<br>  //4. 事件绑定 处理服务端返回的结果<br>  // on  when 当....时候<br>  // readystate 是 xhr 对象中的属性, 表示状态 0 1 2 3 4<br>  // change  改变<br>  xhr.onreadystatechange = function () &#123;<br>    //判断 (服务端返回了所有的结果)<br>    if (xhr.readyState === 4) &#123;<br>      //判断响应状态码 200  404  403 401 500<br>      // 2xx 成功<br>      if (xhr.status &gt;= 200 &amp;&amp; xhr.status &lt; 300) &#123;<br>        //处理结果  行 头 空行 体<br>        //响应 <br>        // console.log(xhr.status);//状态码<br>        // console.log(xhr.statusText);//状态字符串<br>        // console.log(xhr.getAllResponseHeaders());//所有响应头<br>        // console.log(xhr.response);//响应体<br>        //设置 result 的文本<br>        result.innerHTML = xhr.response;<br>      &#125; else &#123;&#125;<br>    &#125;<br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="1-2-Post方式"><a href="#1-2-Post方式" class="headerlink" title="1.2 Post方式"></a>1.2 Post方式</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">//绑定事件</span><br>   result.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">&quot;mouseover&quot;</span>, <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br>       <span class="hljs-comment">//1. 创建对象</span><br>       <span class="hljs-keyword">const</span> xhr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">XMLHttpRequest</span>();<br>       <span class="hljs-comment">//2. 初始化 设置类型与 URL</span><br>       xhr.<span class="hljs-title function_">open</span>(<span class="hljs-string">&#x27;POST&#x27;</span>, <span class="hljs-string">&#x27;http://127.0.0.1:8000/server&#x27;</span>);<br>       <span class="hljs-comment">//设置请求头</span><br>       xhr.<span class="hljs-title function_">setRequestHeader</span>(<span class="hljs-string">&#x27;Content-Type&#x27;</span>,<span class="hljs-string">&#x27;application/x-www-form-urlencoded&#x27;</span>);<br>       xhr.<span class="hljs-title function_">setRequestHeader</span>(<span class="hljs-string">&#x27;name&#x27;</span>,<span class="hljs-string">&#x27;atguigu&#x27;</span>);<br>       <span class="hljs-comment">//3. 发送</span><br>       xhr.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;a=100&amp;b=200&amp;c=300&#x27;</span>);<br>       <span class="hljs-comment">// xhr.send(&#x27;a:100&amp;b:200&amp;c:300&#x27;);</span><br>       <span class="hljs-comment">// xhr.send(&#x27;1233211234567&#x27;);</span><br>       <span class="hljs-comment">//4. 事件绑定</span><br>       xhr.<span class="hljs-property">onreadystatechange</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br>           <span class="hljs-comment">//判断</span><br>           <span class="hljs-keyword">if</span>(xhr.<span class="hljs-property">readyState</span> === <span class="hljs-number">4</span>)&#123;<br>               <span class="hljs-keyword">if</span>(xhr.<span class="hljs-property">status</span> &gt;= <span class="hljs-number">200</span> &amp;&amp; xhr.<span class="hljs-property">status</span> &lt; <span class="hljs-number">300</span>)&#123;<br>                   <span class="hljs-comment">//处理服务端返回的结果</span><br>                   result.<span class="hljs-property">innerHTML</span> = xhr.<span class="hljs-property">response</span>;<br>               &#125;<br>           &#125;<br>       &#125;<br>   &#125;);<br></code></pre></td></tr></table></figure>

<h3 id="1-3-解决ie缓存问题"><a href="#1-3-解决ie缓存问题" class="headerlink" title="1.3 解决ie缓存问题"></a>1.3 解决ie缓存问题</h3><p>问题：在一些浏览器中(IE),由于<code>缓存机制</code>的存在，ajax 只会发送的第一次请求，剩余多次请求不会再发送给浏览器而是直接加载缓存中的数据。</p>
<p>解决方式：浏览器的缓存是根据 url地址来记录的，所以我们只需要修改 url 地址 即可避免缓存问题 <code>xhr.open(&quot;get&quot;,&quot;/testAJAX?t=&quot;+Date.now());</code></p>
<h3 id="1-4-请求超时与网络异常"><a href="#1-4-请求超时与网络异常" class="headerlink" title="1.4 请求超时与网络异常"></a>1.4 请求超时与网络异常</h3><p>当你的请求时间过长,或者无网络时,进行的相应处理</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs js">btn.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">&#x27;click&#x27;</span>, <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br>         <span class="hljs-keyword">const</span> xhr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">XMLHttpRequest</span>();<br>         <span class="hljs-comment">//超时设置 2s 设置</span><br>         xhr.<span class="hljs-property">timeout</span> = <span class="hljs-number">2000</span>;<br>         <span class="hljs-comment">//超时回调</span><br>         xhr.<span class="hljs-property">ontimeout</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br>             <span class="hljs-title function_">alert</span>(<span class="hljs-string">&quot;网络异常, 请稍后重试!!&quot;</span>);<br>         &#125;<br>         <span class="hljs-comment">//网络异常回调</span><br>         xhr.<span class="hljs-property">onerror</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br>             <span class="hljs-title function_">alert</span>(<span class="hljs-string">&quot;你的网络似乎出了一些问题!&quot;</span>);<br>         &#125;<br><br>         xhr.<span class="hljs-title function_">open</span>(<span class="hljs-string">&quot;GET&quot;</span>,<span class="hljs-string">&#x27;http://127.0.0.1:8000/delay&#x27;</span>);<br>         xhr.<span class="hljs-title function_">send</span>();<br>         xhr.<span class="hljs-property">onreadystatechange</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br>             <span class="hljs-keyword">if</span>(xhr.<span class="hljs-property">readyState</span> === <span class="hljs-number">4</span>)&#123;<br>                 <span class="hljs-keyword">if</span>(xhr.<span class="hljs-property">status</span> &gt;= <span class="hljs-number">200</span> &amp;&amp; xhr.<span class="hljs-property">status</span>&lt; <span class="hljs-number">300</span>)&#123;<br>                     result.<span class="hljs-property">innerHTML</span> = xhr.<span class="hljs-property">response</span>;<br>                 &#125;<br>             &#125;<br>         &#125;<br>     &#125;)<br></code></pre></td></tr></table></figure>

<h3 id="1-5-取消请求"><a href="#1-5-取消请求" class="headerlink" title="1.5 取消请求"></a>1.5 取消请求</h3><p>在请求发出去后<code>但是未响应完成</code>时可以进行取消请求操作</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> btns = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">querySelectorAll</span>(<span class="hljs-string">&#x27;button&#x27;</span>);<br><span class="hljs-keyword">let</span> x = <span class="hljs-literal">null</span>;<br>btns[<span class="hljs-number">0</span>].<span class="hljs-property">onclick</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br>    x = <span class="hljs-keyword">new</span> <span class="hljs-title class_">XMLHttpRequest</span>();<br>    x.<span class="hljs-title function_">open</span>(<span class="hljs-string">&quot;GET&quot;</span>,<span class="hljs-string">&#x27;http://127.0.0.1:8000/delay&#x27;</span>);<br>    x.<span class="hljs-title function_">send</span>();<br>&#125;<br><span class="hljs-comment">// abort</span><br>btns[<span class="hljs-number">1</span>].<span class="hljs-property">onclick</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br>    x.<span class="hljs-title function_">abort</span>();<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="1-6-重复请求问题"><a href="#1-6-重复请求问题" class="headerlink" title="1.6 重复请求问题"></a>1.6 重复请求问题</h3><p>利用之前Ⅴ中取消请求知识点,当我点击时判断之前请求是否在发送中,如果是,则停止请求</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs js">btns[<span class="hljs-number">0</span>].<span class="hljs-property">onclick</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br>         <span class="hljs-comment">//判断标识变量</span><br>         <span class="hljs-keyword">if</span>(isSending) x.<span class="hljs-title function_">abort</span>();<span class="hljs-comment">// 如果正在发送, 则取消该请求, 创建一个新的请求</span><br>         x = <span class="hljs-keyword">new</span> <span class="hljs-title class_">XMLHttpRequest</span>();<br>         <span class="hljs-comment">//修改 标识变量的值</span><br>         isSending = <span class="hljs-literal">true</span>;<br>         x.<span class="hljs-title function_">open</span>(<span class="hljs-string">&quot;GET&quot;</span>,<span class="hljs-string">&#x27;http://127.0.0.1:8000/delay&#x27;</span>);<br>         x.<span class="hljs-title function_">send</span>();<br>         x.<span class="hljs-property">onreadystatechange</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br>             <span class="hljs-keyword">if</span>(x.<span class="hljs-property">readyState</span> === <span class="hljs-number">4</span>)&#123;<br>                 <span class="hljs-comment">//修改标识变量</span><br>                 isSending = <span class="hljs-literal">false</span>;<br>             &#125;<br>         &#125;<br>     &#125;<br></code></pre></td></tr></table></figure>

<h1 id="三、常见三种Ajax请求方式"><a href="#三、常见三种Ajax请求方式" class="headerlink" title="三、常见三种Ajax请求方式"></a>三、常见三种Ajax请求方式</h1><h2 id="1-jQuery发送AJAX请求"><a href="#1-jQuery发送AJAX请求" class="headerlink" title="1. jQuery发送AJAX请求"></a>1. jQuery发送AJAX请求</h2><p>jQuery有三种发送请求方法:</p>
<p>当你只是简单的请求数据,可以直接使用前两种方式请求,当你需要设置的东西较多的时候,可以使用<code>$.ajax()</code>方法</p>
<h3 id="1-1-get"><a href="#1-1-get" class="headerlink" title="1.1 $.get()"></a>1.1 $.get()</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js">$(<span class="hljs-string">&#x27;button&#x27;</span>).<span class="hljs-title function_">eq</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">click</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br>          $.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;http://127.0.0.1:8000/jquery-server&#x27;</span>, &#123;<span class="hljs-attr">a</span>:<span class="hljs-number">100</span>, <span class="hljs-attr">b</span>:<span class="hljs-number">200</span>&#125;, <span class="hljs-keyword">function</span>(<span class="hljs-params">data</span>)&#123;<br>              <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);<br>          &#125;,<span class="hljs-string">&#x27;json&#x27;</span>);<br>      &#125;);<br></code></pre></td></tr></table></figure>

<h3 id="1-2-post"><a href="#1-2-post" class="headerlink" title="1.2 $.post()"></a>1.2 $.post()</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js">$(<span class="hljs-string">&#x27;button&#x27;</span>).<span class="hljs-title function_">eq</span>(<span class="hljs-number">1</span>).<span class="hljs-title function_">click</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br>          $.<span class="hljs-title function_">post</span>(<span class="hljs-string">&#x27;http://127.0.0.1:8000/jquery-server&#x27;</span>, &#123;<span class="hljs-attr">a</span>:<span class="hljs-number">100</span>, <span class="hljs-attr">b</span>:<span class="hljs-number">200</span>&#125;, <span class="hljs-keyword">function</span>(<span class="hljs-params">data</span>)&#123;<br>              <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);<br>          &#125;);<br>      &#125;);<br></code></pre></td></tr></table></figure>

<h3 id="1-3-ajax"><a href="#1-3-ajax" class="headerlink" title="1.3 $.ajax"></a>1.3 $.ajax</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><code class="hljs js">$(<span class="hljs-string">&#x27;button&#x27;</span>).<span class="hljs-title function_">eq</span>(<span class="hljs-number">2</span>).<span class="hljs-title function_">click</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br>          $.<span class="hljs-title function_">ajax</span>(&#123;<br>              <span class="hljs-comment">//url</span><br>              <span class="hljs-attr">url</span>: <span class="hljs-string">&#x27;http://127.0.0.1:8000/jquery-server&#x27;</span>,<br>              <span class="hljs-comment">//参数</span><br>              <span class="hljs-attr">data</span>: &#123;<span class="hljs-attr">a</span>:<span class="hljs-number">100</span>, <span class="hljs-attr">b</span>:<span class="hljs-number">200</span>&#125;,<br>              <span class="hljs-comment">//请求类型</span><br>              <span class="hljs-attr">type</span>: <span class="hljs-string">&#x27;GET&#x27;</span>,<br>              <span class="hljs-comment">//响应体结果</span><br>              <span class="hljs-attr">dataType</span>: <span class="hljs-string">&#x27;json&#x27;</span>,<br>              <span class="hljs-comment">//成功的回调</span><br>              <span class="hljs-attr">success</span>: <span class="hljs-keyword">function</span>(<span class="hljs-params">data</span>)&#123;<br>                  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);<br>              &#125;,<br>              <span class="hljs-comment">//超时时间</span><br>              <span class="hljs-attr">timeout</span>: <span class="hljs-number">2000</span>,<br>              <span class="hljs-comment">//失败的回调</span><br>              <span class="hljs-attr">error</span>: <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br>                  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;出错啦!!&#x27;</span>);<br>              &#125;,<br>              <span class="hljs-comment">//头信息</span><br>              <span class="hljs-attr">headers</span>: &#123;<br>                  <span class="hljs-attr">c</span>:<span class="hljs-number">300</span>,<br>                  <span class="hljs-attr">d</span>:<span class="hljs-number">400</span><br>              &#125;<br>          &#125;);<br>      &#125;);<br></code></pre></td></tr></table></figure>

<h2 id="2-Axios发送AJAX请求"><a href="#2-Axios发送AJAX请求" class="headerlink" title="2. Axios发送AJAX请求"></a>2. Axios发送AJAX请求</h2><h3 id="2-1-axios-get"><a href="#2-1-axios-get" class="headerlink" title="2.1 axios.get()"></a>2.1 axios.get()</h3><p>axios.get(url,data,params)</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">//配置 baseURL</span><br>   axios.<span class="hljs-property">defaults</span>.<span class="hljs-property">baseURL</span> = <span class="hljs-string">&#x27;http://127.0.0.1:8000&#x27;</span>;<br><br>   btns[<span class="hljs-number">0</span>].<span class="hljs-property">onclick</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>     <span class="hljs-comment">//GET 请求</span><br>     axios.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/axios-server&#x27;</span>, &#123;<br>       <span class="hljs-comment">//url 参数</span><br>       <span class="hljs-attr">params</span>: &#123;<br>         <span class="hljs-attr">id</span>: <span class="hljs-number">100</span>,<br>         <span class="hljs-attr">vip</span>: <span class="hljs-number">7</span><br>       &#125;,<br>       <span class="hljs-comment">//请求头信息</span><br>       <span class="hljs-attr">headers</span>: &#123;<br>         <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;atguigu&#x27;</span>,<br>         <span class="hljs-attr">age</span>: <span class="hljs-number">20</span><br>       &#125;<br>     &#125;).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> &#123;<br>       <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value);<br>     &#125;);<br>   &#125;<br></code></pre></td></tr></table></figure>

<h4 id="2-2-axios-get"><a href="#2-2-axios-get" class="headerlink" title="2.2 axios.get()"></a>2.2 axios.get()</h4><p>axios.post(url,data,params)</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">//配置 baseURL</span><br>    axios.<span class="hljs-property">defaults</span>.<span class="hljs-property">baseURL</span> = <span class="hljs-string">&#x27;http://127.0.0.1:8000&#x27;</span>;  <br>	btns[<span class="hljs-number">1</span>].<span class="hljs-property">onclick</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>      axios.<span class="hljs-title function_">post</span>(<span class="hljs-string">&#x27;/axios-server&#x27;</span>, &#123;<br>        <span class="hljs-attr">username</span>: <span class="hljs-string">&#x27;admin&#x27;</span>,<br>        <span class="hljs-attr">password</span>: <span class="hljs-string">&#x27;admin&#x27;</span><br>      &#125;, &#123;<br>        <span class="hljs-comment">//url </span><br>        <span class="hljs-attr">params</span>: &#123;<br>          <span class="hljs-attr">id</span>: <span class="hljs-number">200</span>,<br>          <span class="hljs-attr">vip</span>: <span class="hljs-number">9</span><br>        &#125;,<br>        <span class="hljs-comment">//请求头参数</span><br>        <span class="hljs-attr">headers</span>: &#123;<br>          <span class="hljs-attr">height</span>: <span class="hljs-number">180</span>,<br>          <span class="hljs-attr">weight</span>: <span class="hljs-number">180</span>,<br>        &#125;<br>      &#125;);<br>    &#125;<br></code></pre></td></tr></table></figure>

<h3 id="1-3-axios-常用"><a href="#1-3-axios-常用" class="headerlink" title="1.3 axios() 常用"></a>1.3 axios() <code>常用</code></h3><p>axios({})</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">//配置 baseURL</span><br>    axios.<span class="hljs-property">defaults</span>.<span class="hljs-property">baseURL</span> = <span class="hljs-string">&#x27;http://127.0.0.1:8000&#x27;</span>;<br>	btns[<span class="hljs-number">2</span>].<span class="hljs-property">onclick</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>      <span class="hljs-title function_">axios</span>(&#123;<br>        <span class="hljs-comment">//请求方法</span><br>        <span class="hljs-attr">method</span>: <span class="hljs-string">&#x27;POST&#x27;</span>,<br>        <span class="hljs-comment">//url</span><br>        <span class="hljs-attr">url</span>: <span class="hljs-string">&#x27;/axios-server&#x27;</span>,<br>        <span class="hljs-comment">//url参数</span><br>        <span class="hljs-attr">params</span>: &#123;<br>          <span class="hljs-attr">vip</span>: <span class="hljs-number">10</span>,<br>          <span class="hljs-attr">level</span>: <span class="hljs-number">30</span><br>        &#125;,<br>        <span class="hljs-comment">//头信息,此部分如果使用自定义的头信息,需要服务端进行相应修改,正常不设置</span><br>        <span class="hljs-attr">headers</span>: &#123;<br>          <span class="hljs-attr">a</span>: <span class="hljs-number">100</span>,<br>          <span class="hljs-attr">b</span>: <span class="hljs-number">200</span><br>        &#125;,<br>        <span class="hljs-comment">//请求体参数</span><br>        <span class="hljs-attr">data</span>: &#123;<br>          <span class="hljs-attr">username</span>: <span class="hljs-string">&#x27;admin&#x27;</span>,<br>          <span class="hljs-attr">password</span>: <span class="hljs-string">&#x27;admin&#x27;</span><br>        &#125;<br>      &#125;).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> &#123;<br>        <span class="hljs-comment">//响应状态码</span><br>        <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(response.<span class="hljs-property">status</span>);<br>        <span class="hljs-comment">//响应状态字符串</span><br>        <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(response.<span class="hljs-property">statusText</span>);<br>        <span class="hljs-comment">//响应头信息</span><br>        <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(response.<span class="hljs-property">headers</span>);<br>        <span class="hljs-comment">//响应体</span><br>        <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(response.<span class="hljs-property">data</span>);<br>      &#125;)<br>    &#125;<br></code></pre></td></tr></table></figure>

<h2 id="3-Fetch发送AJAX请求"><a href="#3-Fetch发送AJAX请求" class="headerlink" title="3. Fetch发送AJAX请求"></a>3. Fetch发送AJAX请求</h2><p>代码示例</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs js">btn.<span class="hljs-property">onclick</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>    <span class="hljs-title function_">fetch</span>(<span class="hljs-string">&#x27;http://127.0.0.1:8000/fetch-server?vip=10&#x27;</span>, &#123;<br>      <span class="hljs-comment">//请求方法</span><br>      <span class="hljs-attr">method</span>: <span class="hljs-string">&#x27;POST&#x27;</span>,<br>      <span class="hljs-comment">//请求头</span><br>      <span class="hljs-attr">headers</span>: &#123;<br>        <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;atguigu&#x27;</span><br>      &#125;,<br>      <span class="hljs-comment">//请求体</span><br>      <span class="hljs-attr">body</span>: <span class="hljs-string">&#x27;username=admin&amp;password=admin&#x27;</span><br>    &#125;).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> &#123;<br>      <span class="hljs-comment">// return response.text();</span><br>      <span class="hljs-keyword">return</span> response.<span class="hljs-title function_">json</span>();<br>    &#125;).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> &#123;<br>      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(response);<br>    &#125;);<br>  &#125;<br></code></pre></td></tr></table></figure>

<h1 id="四、跨域与解决"><a href="#四、跨域与解决" class="headerlink" title="四、跨域与解决"></a>四、跨域与解决</h1><h5 id="1、什么是跨越？"><a href="#1、什么是跨越？" class="headerlink" title="1、什么是跨越？"></a>1、什么是跨越？</h5><ul>
<li>一个网页向另一个不同域名&#x2F;不同协议&#x2F;不同端口的网页请求资源，这就是跨域。</li>
<li>跨域原因产生：在当前域名请求网站中，默认不允许通过ajax请求发送其他域名。</li>
</ul>
<h5 id="2、为什么会产生跨域请求？"><a href="#2、为什么会产生跨域请求？" class="headerlink" title="2、为什么会产生跨域请求？"></a>2、为什么会产生跨域请求？</h5><ul>
<li>因为浏览器使用了同源策略</li>
</ul>
<h5 id="3、什么是同源策略？"><a href="#3、什么是同源策略？" class="headerlink" title="3、什么是同源策略？"></a>3、什么是同源策略？</h5><ul>
<li>同源策略是Netscape提出的一个著名的安全策略，现在所有支持JavaScript的浏览器都会使用这个策略。同源策略是浏览器最核心也最基本的安全功能，如果缺少同源策略，浏览器的正常功能可能受到影响。可以说web是构建在同源策略的基础之上的，浏览器只是针对同源策略的一种实现。</li>
<li>同源： 协议、域名、端口号 必须完全相同。 <code>违背同源策略就是跨域</code>。</li>
</ul>
<h5 id="4、为什么浏览器要使用同源策略？"><a href="#4、为什么浏览器要使用同源策略？" class="headerlink" title="4、为什么浏览器要使用同源策略？"></a>4、为什么浏览器要使用同源策略？</h5><ul>
<li>是为了保证用户的信息安全，防止恶意网站窃取数据，如果网页之间不满足同源要求，将不能:</li>
<li><ul>
<li>1、共享Cookie、LocalStorage、IndexDB</li>
</ul>
</li>
<li><ul>
<li>2、获取DOM</li>
</ul>
</li>
<li><ul>
<li>3、AJAX请求不能发送</li>
</ul>
</li>
</ul>
<h5 id="5、跨域的五个解决方式"><a href="#5、跨域的五个解决方式" class="headerlink" title="5、跨域的五个解决方式:"></a>5、跨域的五个解决方式:</h5><p>​    1、前端使用jsonp （不推荐使用）</p>
<p>​    2、后台Http请求转发</p>
<p>​    3、后台配置同源Cors （推荐）</p>
<p>​    4、使用SpringCloud网关</p>
<p>​    5、使用nginx做转发 (推荐)</p>
<h2 id="1-jsonP"><a href="#1-jsonP" class="headerlink" title="1. jsonP"></a>1. jsonP</h2><p>1)JSONP 是什么?</p>
<p>​    JSONP(JSON with Padding)，是一个非官方的跨域解决方案，纯粹凭借程序员的聪明 才智开发出来，只支持 get 请求。</p>
<p>2)JSONP 怎么工作的？</p>
<p>​    在网页有一些标签天生具有跨域能力，比如：img link iframe script。 JSONP 就是利用 script 标签的跨域能力来发送请求的。</p>
<h3 id="1-1-jsonP的使用"><a href="#1-1-jsonP的使用" class="headerlink" title="1.1 jsonP的使用"></a>1.1 jsonP的使用</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 1. 动态的创建一个 script 标签------------------------------------------------------------</span><br>    <span class="hljs-keyword">var</span> script = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">createElement</span>(<span class="hljs-string">&quot;script&quot;</span>);<br>	<span class="hljs-comment">//2. 设置 script 的 src， 设置回调函数</span><br>    script.<span class="hljs-property">src</span> = <span class="hljs-string">&quot;http://localhost:3000/testAJAX?callback=abc&quot;</span>;<br>    <span class="hljs-keyword">function</span> <span class="hljs-title function_">abc</span>(<span class="hljs-params">data</span>) &#123;<br>      <span class="hljs-title function_">alert</span>(data.<span class="hljs-property">name</span>);<br>    &#125;;<br>   <span class="hljs-comment">// 3. 将 script 添加到 body 中</span><br>    <span class="hljs-variable language_">document</span>.<span class="hljs-property">body</span>.<span class="hljs-title function_">appendChild</span>(script);<br><br>   <span class="hljs-comment">// 4. 服务器中路由的处理------------------------------------------------------</span><br>    router.<span class="hljs-title function_">get</span>(<span class="hljs-string">&quot;/testAJAX&quot;</span>, <span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) &#123;<br>      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&quot;收到请求&quot;</span>);<br>      <span class="hljs-keyword">var</span> callback = req.<span class="hljs-property">query</span>.<span class="hljs-property">callback</span>;<br>      <span class="hljs-keyword">var</span> obj = &#123;<br>        <span class="hljs-attr">ame</span>: <span class="hljs-string">&quot;孙悟空&quot;</span>,<br>        <span class="hljs-attr">age</span>: <span class="hljs-number">18</span><br>      &#125;<br>      res.<span class="hljs-title function_">send</span>(callback + <span class="hljs-string">&quot;(&quot;</span> + <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(obj) + <span class="hljs-string">&quot;)&quot;</span>);<br>    &#125;);<br></code></pre></td></tr></table></figure>

<h3 id="1-2-jQuery发送jsonP请求"><a href="#1-2-jQuery发送jsonP请求" class="headerlink" title="1.2 jQuery发送jsonP请求"></a>1.2 jQuery发送jsonP请求</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">//前端代码-----------------------------------------------------------------------------------</span><br>$(<span class="hljs-string">&#x27;button&#x27;</span>).<span class="hljs-title function_">eq</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">click</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>  $.<span class="hljs-title function_">getJSON</span>(<span class="hljs-string">&#x27;http://127.0.0.1:8000/jquery-jsonp-server?callback=?&#x27;</span>, <span class="hljs-keyword">function</span> (<span class="hljs-params">data</span>) &#123;<br>    $(<span class="hljs-string">&#x27;#result&#x27;</span>).<span class="hljs-title function_">html</span>(<span class="hljs-string">`</span><br><span class="hljs-string">                名称: <span class="hljs-subst">$&#123;data.name&#125;</span>&lt;br&gt;</span><br><span class="hljs-string">                校区: <span class="hljs-subst">$&#123;data.city&#125;</span></span><br><span class="hljs-string">            `</span>)<br>  &#125;);<br>&#125;);<br><br><span class="hljs-comment">//服务端代码-----------------------------------------------------------</span><br>app.<span class="hljs-title function_">all</span>(<span class="hljs-string">&#x27;/jquery-jsonp-server&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">// response.send(&#x27;console.log(&quot;hello jsonp&quot;)&#x27;);</span><br>  <span class="hljs-keyword">const</span> data = &#123;<br>    <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;尚硅谷&#x27;</span>,<br>    <span class="hljs-attr">city</span>: [<span class="hljs-string">&#x27;北京&#x27;</span>, <span class="hljs-string">&#x27;上海&#x27;</span>, <span class="hljs-string">&#x27;深圳&#x27;</span>]<br>  &#125;;<br>  <span class="hljs-comment">//将数据转化为字符串</span><br>  <span class="hljs-keyword">let</span> str = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(data);<br>  <span class="hljs-comment">//接收 callback 参数</span><br>  <span class="hljs-keyword">let</span> cb = request.<span class="hljs-property">query</span>.<span class="hljs-property">callback</span>;<br><br>  <span class="hljs-comment">//返回结果</span><br>  response.<span class="hljs-title function_">end</span>(<span class="hljs-string">`<span class="hljs-subst">$&#123;cb&#125;</span>(<span class="hljs-subst">$&#123;str&#125;</span>)`</span>);<br>&#125;);<br></code></pre></td></tr></table></figure>

<h3 id="1-3-自己开发封装的jsonP插件"><a href="#1-3-自己开发封装的jsonP插件" class="headerlink" title="1.3 自己开发封装的jsonP插件"></a>1.3 自己开发封装的jsonP插件</h3><blockquote>
<p>1、代价:需要前后端联动<br>2、精髓:自动的由插件生成方法名,并在当前的页面动态的生成函数,然后再生成的函数里头调用用户预留的回调函数<br>3、插件：自动化的去模拟基于script去实现跨域请求的过程（对用户来说是黑盒子）<br>4、参数拼接：url已经是带参的。和不带参的<br>5、id优化 额可以添加一个容器来管理id</p>
</blockquote>
<blockquote>
<p>1、前端调用测试封装好的jsonP代码</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">//测试调用函数</span><br>    <span class="hljs-keyword">let</span> test=<span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>        jsonP.<span class="hljs-title function_">req</span>(&#123;<br>            <span class="hljs-attr">url</span>:<span class="hljs-string">&quot;http://localhost:3000/jsonpx&quot;</span>,<br>            <span class="hljs-attr">data</span>:&#123;<br>                <span class="hljs-attr">a</span>:<span class="hljs-string">&quot;111&quot;</span><br>            &#125;,<br>            <span class="hljs-attr">callback</span>:<span class="hljs-keyword">function</span> (<span class="hljs-params">result</span>) &#123;<br>                <span class="hljs-title function_">alert</span>(<span class="hljs-string">&quot;成功&quot;</span>+result)<br>            &#125;<br>        &#125;)<br>    &#125;<br></code></pre></td></tr></table></figure>

<p>2、服务端测试代码</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs js">router.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/jsonpx&#x27;</span>, <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> (<span class="hljs-params">req, resp, next</span>) &#123;<br>    <span class="hljs-keyword">let</span> callback=req.<span class="hljs-property">query</span>.<span class="hljs-property">callback</span>;<br>    <span class="hljs-keyword">let</span> data=req.<span class="hljs-property">query</span>.<span class="hljs-property">a</span>;<br>    <span class="hljs-keyword">if</span> (!data)&#123;<br>        resp.<span class="hljs-title function_">send</span>(<span class="hljs-string">`<span class="hljs-subst">$&#123;callback&#125;</span>(&#x27;洪jl:我是服务端代码&#x27;)`</span>)<br>    &#125;<br>    resp.<span class="hljs-title function_">send</span>(<span class="hljs-string">`<span class="hljs-subst">$&#123;callback&#125;</span>(&#x27;洪jl:我是服务端代码`</span>+data+<span class="hljs-string">`&#x27;)`</span>)<br>&#125;)<br></code></pre></td></tr></table></figure>

<p>3、封装原生代码</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br></pre></td><td class="code"><pre><code class="hljs js">&lt;script&gt;<br>    <span class="hljs-comment">/**author:<span class="hljs-doctag">@hongjilin</span></span><br><span class="hljs-comment">     * 1.声明一个jsonP插件对象</span><br><span class="hljs-comment">     * 作用：隔开作用域</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">let</span> jsonP = &#123;&#125;;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     *2.在插件对象中创建两个名字备用符数组</span><br><span class="hljs-comment">     */</span><br>    jsonP.<span class="hljs-property">char</span> = &#123;<br>        <span class="hljs-title class_">Number</span>: <span class="hljs-string">&#x27;0123456789&#x27;</span>,<br>        <span class="hljs-title class_">Letter</span>: <span class="hljs-string">&#x27;qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM&#x27;</span><br>    &#125;<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 通过随机数抽取备用字符数组库拼凑函数id</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> <span class="hljs-variable">charLen</span></span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> <span class="hljs-variable">numLen</span></span><br><span class="hljs-comment">     */</span><br>    jsonP.<span class="hljs-property">newFunId</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params">charLen, numLen</span>) &#123;<br>        <span class="hljs-keyword">let</span> id = <span class="hljs-string">&#x27;&#x27;</span>;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; charLen; i++) &#123;<br>            id += <span class="hljs-variable language_">this</span>.<span class="hljs-property">char</span>.<span class="hljs-property">Letter</span>.<span class="hljs-title function_">charAt</span>(<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">random</span>() * <span class="hljs-number">52</span>)<br>        &#125;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = <span class="hljs-number">0</span>; j &lt; numLen; j++) &#123;<br>            id += <span class="hljs-title class_">Math</span>.<span class="hljs-title function_">floor</span>(<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">random</span>() * <span class="hljs-number">10</span>);<br>        &#125;<br>        <span class="hljs-keyword">return</span> id;<br>    &#125;<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 拼接路径</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> <span class="hljs-variable">url</span></span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> <span class="hljs-variable">key</span></span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> <span class="hljs-variable">value</span></span><br><span class="hljs-comment">     */</span><br>    jsonP.<span class="hljs-property">jointUrl</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params">url, key, value</span>) &#123;<br>        <span class="hljs-keyword">if</span> (url &amp;&amp; key &amp;&amp; value) &#123;<br>            <span class="hljs-keyword">let</span> sign = <span class="hljs-string">&quot;&amp;&quot;</span><br>            <span class="hljs-comment">//如果是第一次</span><br>            <span class="hljs-keyword">if</span> (url.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">&#x27;?&#x27;</span>) == -<span class="hljs-number">1</span>) &#123;<br>                sign = <span class="hljs-string">&#x27;?&#x27;</span><br>            &#125;<br><br>            url += sign + key + <span class="hljs-string">&quot;=&quot;</span> + value<br>        &#125;<br>        <span class="hljs-keyword">return</span> url;<br>    &#125;<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     封装err属性方便</span><br><span class="hljs-comment">     */</span><br>    jsonP.<span class="hljs-property">err</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params">msg</span>) &#123;<br>        <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(msg)<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 发送请求函数</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> <span class="hljs-variable">options</span></span><br><span class="hljs-comment">     */</span><br>    jsonP.<span class="hljs-property">req</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params">options</span>) &#123;<br>        <span class="hljs-keyword">let</span> jsonId=&#123;&#125;;<br>        <span class="hljs-comment">//1.生成方法名</span><br>        jsonId.<span class="hljs-property">funId</span> = <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">newFunId</span>(<span class="hljs-number">4</span>,<span class="hljs-number">8</span>);<br>        <span class="hljs-keyword">let</span> <span class="hljs-title class_">Userurl</span> = options.<span class="hljs-property">url</span>;<br>        <span class="hljs-keyword">let</span> <span class="hljs-title class_">Userdata</span> = options.<span class="hljs-property">data</span>;<br>        <span class="hljs-keyword">if</span> (!options) &#123;<br>            <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">err</span>(<span class="hljs-string">&quot;输入不能空&quot;</span>)<br>            <span class="hljs-keyword">return</span>;<br>        &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (!<span class="hljs-title class_">Userurl</span>) &#123;<br>            <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">err</span>(<span class="hljs-string">&quot;url不能空&quot;</span>)<br>            <span class="hljs-keyword">return</span>;<br>        &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (!<span class="hljs-title class_">Userdata</span>) &#123;<br>            <span class="hljs-comment">//如果没有data,初始化</span><br>            <span class="hljs-title class_">Userdata</span> = &#123;&#125;;<br>        &#125;<br>        <span class="hljs-comment">//将函数名赋值给userdata的回调函数属性中</span><br>        <span class="hljs-title class_">Userdata</span>.<span class="hljs-property">callback</span> = jsonId.<span class="hljs-property">funId</span>;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> key <span class="hljs-keyword">in</span> <span class="hljs-title class_">Userdata</span>) &#123;<br>            <span class="hljs-title class_">Userurl</span> = <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">jointUrl</span>(<span class="hljs-title class_">Userurl</span>, key, <span class="hljs-title class_">Userdata</span>[key])<br>        &#125;<br>        <span class="hljs-keyword">let</span> script = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">createElement</span>(<span class="hljs-string">&#x27;script&#x27;</span>);<br>        script.<span class="hljs-title function_">setAttribute</span>(<span class="hljs-string">&quot;id&quot;</span> , jsonId.<span class="hljs-property">funId</span>);<br>        script.<span class="hljs-title function_">setAttribute</span>(<span class="hljs-string">&quot;src&quot;</span> , <span class="hljs-title class_">Userurl</span>);<br>        <span class="hljs-comment">//动态生成函数</span><br>        <span class="hljs-keyword">let</span> callback=<span class="hljs-keyword">function</span> (<span class="hljs-params">result</span>) &#123;<br>            <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&quot;xxxxxxx&quot;</span>)<br>            <span class="hljs-comment">//业务逻辑回调</span><br>            <span class="hljs-keyword">if</span> (options.<span class="hljs-property">callback</span>)&#123;<br>                <span class="hljs-keyword">try</span> &#123;<br>                    options.<span class="hljs-title function_">callback</span>(result)<br>                &#125;<span class="hljs-keyword">catch</span> (e) &#123;<br>                    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">err</span>(e.<span class="hljs-property">message</span>)<br>                &#125;<br>            &#125;<br>            <span class="hljs-comment">//善后</span><br>            <span class="hljs-keyword">let</span> tmp=<span class="hljs-variable language_">document</span>.<span class="hljs-title function_">getElementById</span>(jsonId.<span class="hljs-property">funId</span>)<br>            tmp.<span class="hljs-property">parentNode</span>.<span class="hljs-title function_">removeChild</span>(tmp);<br>            <span class="hljs-built_in">eval</span>(jsonId.<span class="hljs-property">funId</span>+<span class="hljs-string">&#x27;=null&#x27;</span>)<br>        &#125;<br>        <span class="hljs-built_in">eval</span>(<span class="hljs-string">&quot;window.&quot;</span>+jsonId.<span class="hljs-property">funId</span>+<span class="hljs-string">&quot;=function(result)&#123; callback(result) &#125;&quot;</span>)<br>        <span class="hljs-variable language_">document</span>.<span class="hljs-property">head</span>.<span class="hljs-title function_">appendChild</span>(script)<br><br>    &#125;<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>
</blockquote>
<h2 id="2、CORS"><a href="#2、CORS" class="headerlink" title="2、CORS"></a>2、CORS</h2><p>1、l链接：<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CORS">https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CORS#http</a></p>
<p>2、CORS是什么?</p>
<p>​    CORS（Cross-Origin Resource Sharing），跨域资源共享。CORS 是官方的跨域解决方 案，它的特点是不需要在客户端做任何特殊的操作，完全在服务器中进行处理，支持 get 和 post 请求。跨域资源共享标准新增了一组 HTTP 首部字段，允许服务器声明哪些 源站通过浏览器有权限访问哪些资源</p>
<p>3、CORS是怎么工作的?</p>
<p>​    CORS 是通过设置一个响应头来告诉浏览器，该请求允许跨域，浏览器收到该响应 以后就会对响应放行。</p>
<h3 id="2-1-代码示例"><a href="#2-1-代码示例" class="headerlink" title="2.1 代码示例"></a>2.1 代码示例</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs js">app.<span class="hljs-title function_">all</span>(<span class="hljs-string">&#x27;/cors-server&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">//设置响应头</span><br>    <span class="hljs-comment">//响应首部中可以携带一个 Access-Control-Allow-Origin 字段</span><br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&quot;Access-Control-Allow-Origin&quot;</span>, <span class="hljs-string">&quot;*&quot;</span>);<br>    <span class="hljs-comment">//Access-Control-Allow-Headers 首部字段用于预检请求的响应。其指明了实际请求中允许携带的首部字</span><br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&quot;Access-Control-Allow-Headers&quot;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);<br>    <span class="hljs-comment">//Access-Control-Allow-Methods 首部字段用于预检请求的响应。其指明了实际请求所允许使用的 HTTP</span><br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&quot;Access-Control-Allow-Method&quot;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);<br>  <span class="hljs-comment">// response.setHeader(&quot;Access-Control-Allow-Origin&quot;, &quot;http://127.0.0.1:5500&quot;);</span><br>  response.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;hello CORS&#x27;</span>);<br>&#125;);<br></code></pre></td></tr></table></figure>

<p>具体的一些参数的使用可以看链接：<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CORS#http">https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CORS#http</a></p>
<h1 id="五、服务端代码示例"><a href="#五、服务端代码示例" class="headerlink" title="五、服务端代码示例"></a>五、服务端代码示例</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">//1. 引入express</span><br><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;express&#x27;</span>);<br><br><span class="hljs-comment">//2. 创建应用对象</span><br><span class="hljs-keyword">const</span> app = <span class="hljs-title function_">express</span>();<br><br><span class="hljs-comment">//3. 创建路由规则</span><br><span class="hljs-comment">// request 是对请求报文的封装</span><br><span class="hljs-comment">// response 是对响应报文的封装</span><br>app.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/server&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">//设置响应头  设置允许跨域</span><br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Origin&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);<br>  <span class="hljs-comment">//设置响应体</span><br>  response.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;HELLO AJAX - 2&#x27;</span>);<br>&#125;);<br><br><span class="hljs-comment">//可以接收任意类型的请求 </span><br>app.<span class="hljs-title function_">all</span>(<span class="hljs-string">&#x27;/server&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">//设置响应头  设置允许跨域</span><br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Origin&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);<br>  <span class="hljs-comment">//响应头</span><br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Headers&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);<br>  <span class="hljs-comment">//设置响应体</span><br>  response.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;HELLO AJAX POST&#x27;</span>);<br>&#125;);<br><br><span class="hljs-comment">//JSON 响应</span><br>app.<span class="hljs-title function_">all</span>(<span class="hljs-string">&#x27;/json-server&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">//设置响应头  设置允许跨域</span><br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Origin&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);<br>  <span class="hljs-comment">//响应头</span><br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Headers&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);<br>  <span class="hljs-comment">//响应一个数据</span><br>  <span class="hljs-keyword">const</span> data = &#123;<br>    <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;atguigu&#x27;</span><br>  &#125;;<br>  <span class="hljs-comment">//对对象进行字符串转换</span><br>  <span class="hljs-keyword">let</span> str = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(data);<br>  <span class="hljs-comment">//设置响应体</span><br>  response.<span class="hljs-title function_">send</span>(str);<br>&#125;);<br><br><span class="hljs-comment">//针对 IE 缓存</span><br>app.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/ie&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">//设置响应头  设置允许跨域</span><br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Origin&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);<br>  <span class="hljs-comment">//设置响应体</span><br>  response.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;HELLO IE - 5&#x27;</span>);<br>&#125;);<br><br><span class="hljs-comment">//延时响应</span><br>app.<span class="hljs-title function_">all</span>(<span class="hljs-string">&#x27;/delay&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">//设置响应头  设置允许跨域</span><br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Origin&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);<br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Headers&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);<br>  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> &#123;<br>    <span class="hljs-comment">//设置响应体</span><br>    response.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;延时响应&#x27;</span>);<br>  &#125;, <span class="hljs-number">1000</span>)<br>&#125;);<br><br><span class="hljs-comment">//jQuery 服务</span><br>app.<span class="hljs-title function_">all</span>(<span class="hljs-string">&#x27;/jquery-server&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">//设置响应头  设置允许跨域</span><br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Origin&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);<br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Headers&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);<br>  <span class="hljs-comment">// response.send(&#x27;Hello jQuery AJAX&#x27;);</span><br>  <span class="hljs-keyword">const</span> data = &#123;<br>    <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;aodi&#x27;</span><br>  &#125;;<br>  response.<span class="hljs-title function_">send</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(data));<br>&#125;);<br><br><span class="hljs-comment">//axios 服务</span><br>app.<span class="hljs-title function_">all</span>(<span class="hljs-string">&#x27;/axios-server&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">//设置响应头  设置允许跨域</span><br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Origin&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);<br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Headers&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);<br>  <span class="hljs-comment">// response.send(&#x27;Hello jQuery AJAX&#x27;);</span><br>  <span class="hljs-keyword">const</span> data = &#123;<br>    <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;尚硅谷&#x27;</span><br>  &#125;;<br>  response.<span class="hljs-title function_">send</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(data));<br>&#125;);<br><br><span class="hljs-comment">//fetch 服务</span><br>app.<span class="hljs-title function_">all</span>(<span class="hljs-string">&#x27;/fetch-server&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">//设置响应头  设置允许跨域</span><br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Origin&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);<br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&#x27;Access-Control-Allow-Headers&#x27;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);<br>  <span class="hljs-comment">// response.send(&#x27;Hello jQuery AJAX&#x27;);</span><br>  <span class="hljs-keyword">const</span> data = &#123;<br>    <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;aodi&#x27;</span><br>  &#125;;<br>  response.<span class="hljs-title function_">send</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(data));<br>&#125;);<br><br><span class="hljs-comment">//jsonp服务</span><br>app.<span class="hljs-title function_">all</span>(<span class="hljs-string">&#x27;/jsonp-server&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">// response.send(&#x27;console.log(&quot;hello jsonp&quot;)&#x27;);</span><br>  <span class="hljs-keyword">const</span> data = &#123;<br>    <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;aodi&#x27;</span><br>  &#125;;<br>  <span class="hljs-comment">//将数据转化为字符串</span><br>  <span class="hljs-keyword">let</span> str = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(data);<br>  <span class="hljs-comment">//返回结果</span><br>  response.<span class="hljs-title function_">end</span>(<span class="hljs-string">`handle(<span class="hljs-subst">$&#123;str&#125;</span>)`</span>);<br>&#125;);<br><br><span class="hljs-comment">//用户名检测是否存在</span><br>app.<span class="hljs-title function_">all</span>(<span class="hljs-string">&#x27;/check-username&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">// response.send(&#x27;console.log(&quot;hello jsonp&quot;)&#x27;);</span><br>  <span class="hljs-keyword">const</span> data = &#123;<br>    <span class="hljs-attr">exist</span>: <span class="hljs-number">1</span>,<br>    <span class="hljs-attr">msg</span>: <span class="hljs-string">&#x27;用户名已经存在&#x27;</span><br>  &#125;;<br>  <span class="hljs-comment">//将数据转化为字符串</span><br>  <span class="hljs-keyword">let</span> str = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(data);<br>  <span class="hljs-comment">//返回结果</span><br>  response.<span class="hljs-title function_">end</span>(<span class="hljs-string">`handle(<span class="hljs-subst">$&#123;str&#125;</span>)`</span>);<br>&#125;);<br><br><span class="hljs-comment">//</span><br>app.<span class="hljs-title function_">all</span>(<span class="hljs-string">&#x27;/jquery-jsonp-server&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">// response.send(&#x27;console.log(&quot;hello jsonp&quot;)&#x27;);</span><br>  <span class="hljs-keyword">const</span> data = &#123;<br>    <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;aodi&#x27;</span>,<br>    <span class="hljs-attr">city</span>: [<span class="hljs-string">&#x27;北京&#x27;</span>, <span class="hljs-string">&#x27;上海&#x27;</span>, <span class="hljs-string">&#x27;深圳&#x27;</span>]<br>  &#125;;<br>  <span class="hljs-comment">//将数据转化为字符串</span><br>  <span class="hljs-keyword">let</span> str = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(data);<br>  <span class="hljs-comment">//接收 callback 参数</span><br>  <span class="hljs-keyword">let</span> cb = request.<span class="hljs-property">query</span>.<span class="hljs-property">callback</span>;<br><br>  <span class="hljs-comment">//返回结果</span><br>  response.<span class="hljs-title function_">end</span>(<span class="hljs-string">`<span class="hljs-subst">$&#123;cb&#125;</span>(<span class="hljs-subst">$&#123;str&#125;</span>)`</span>);<br>&#125;);<br><br>app.<span class="hljs-title function_">all</span>(<span class="hljs-string">&#x27;/cors-server&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">request, response</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">//设置响应头</span><br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&quot;Access-Control-Allow-Origin&quot;</span>, <span class="hljs-string">&quot;*&quot;</span>);<br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&quot;Access-Control-Allow-Headers&quot;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);<br>  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">&quot;Access-Control-Allow-Method&quot;</span>, <span class="hljs-string">&#x27;*&#x27;</span>);<br>  <span class="hljs-comment">// response.setHeader(&quot;Access-Control-Allow-Origin&quot;, &quot;http://127.0.0.1:5500&quot;);</span><br>  response.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;hello CORS&#x27;</span>);<br>&#125;);<br><br><span class="hljs-comment">//4. 监听端口启动服务</span><br>app.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>, <span class="hljs-function">() =&gt;</span> &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&quot;服务已经启动, 8000 端口监听中....&quot;</span>);<br>&#125;);<br></code></pre></td></tr></table></figure>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
              </div>
              <p class="note note-warning">
                <strong>本文作者: </strong><a href="/HexoPage/">xiao_aodi</a> <br>
                <!-- <strong>本文链接: </strong><a href="http://xiao_aodi.gitee.io/hexopage/2022/03/23/Ajax%E8%AE%B0%E5%BD%95(%E8%AF%A6%E8%A7%A3)/">http://xiao_aodi.gitee.io/hexopage/2022/03/23/Ajax%E8%AE%B0%E5%BD%95(%E8%AF%A6%E8%A7%A3)/</a> <br> -->
                <strong>版权声明: </strong>本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                   </p>
                   

              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/HexoPage/2022/03/24/Promise%E7%AC%94%E8%AE%B0/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Promise的理解与使用(快速上手版）</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/HexoPage/2022/03/23/JavaScript%E5%AD%A6%E4%B9%A0%E5%B7%A9%E5%9B%BA%E5%9F%BA%E7%A1%80%E5%A4%96%E5%8A%A0%E8%BF%9B%E9%98%B6(%E4%B8%8B)%E5%BA%95%E5%B1%82%E5%8E%9F%E7%90%86/">
                        <span class="hidden-mobile">JavaScript学习巩固基础外加进阶(下)底层原理</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  
   <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a>  
  <!-- 添加网站运行时间 -->
  <div class="footer-content">
    <div>
      <span id="timeDate">载入天数...</span>
      <span id="times">载入时分秒...</span>
      <script>
      var now = new Date();
      function createtime(){
          var grt= new Date("03/10/2022 00:00:00");//此处修改你的建站时间或者网站上线时间
          now.setTime(now.getTime()+250);
          days = (now - grt ) / 1000 / 60 / 60 / 24;
          dnum = Math.floor(days);
          hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum);
          hnum = Math.floor(hours);
          if(String(hnum).length ==1 ){
              hnum = "0" + hnum;
          }
          minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum);
          mnum = Math.floor(minutes);
          if(String(mnum).length ==1 ){
                    mnum = "0" + mnum;
          }
          seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
          snum = Math.round(seconds);
          if(String(snum).length ==1 ){
                    snum = "0" + snum;
          }
          document.getElementById("timeDate").innerHTML = "🚀 &nbsp"+dnum+"&nbsp天";  //此次自定义显示内容
          document.getElementById("times").innerHTML = hnum + "&nbsp小时&nbsp" + mnum + "&nbsp分&nbsp" + snum + "&nbsp秒";
      }  //此次自定义显示内容
      setInterval("createtime()",250);
      </script>
    </div>
  </div>
  <!-- 统计访问量信息 -->
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  <!-- 个人和备案信息 -->
  <div>©2022-2023<a target="_blank" rel="noopener" href="https://clearlight.blog.csdn.net/">ClearlightY</a> <a target="_blank" rel="noopener" href="http://beian.miit.gov.cn/">冀ICP备19019307号-2</a></div>
   
  <!-- 备案信息 -->
  <div class="beian">
    <span>
      <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
        京ICP证123456号
      </a>
    </span>
    
      
        <span>
          <a
            href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=12345678"
            rel="nofollow noopener"
            class="beian-police"
            target="_blank"
          >
            
              <span style="visibility: hidden; width: 0">|</span>
              <img src="/HexoPage/img/police_beian.png" alt="police-icon"/>
            
            <span>京公网安备12345678号</span>
          </a>
        </span>
      
    
  </div>


  
</footer>

<!-- SCRIPTS -->

  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/HexoPage/js/events.js" ></script>
<script  src="/HexoPage/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/HexoPage/js/local-search.js" ></script>





  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/HexoPage/js/boot.js" ></script>




  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/HexoPage/js/events.js" ></script>
<script  src="/HexoPage/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/HexoPage/js/local-search.js" ></script>





  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/HexoPage/js/boot.js" ></script>


</body>
</html>
